﻿/*-----------------------------------------------
// File: DropAngerBallUI.cs
// Description: 
// Author: Shaobing	492057342@qq.com
-----------------------------------------------*/
using UnityEngine;
using System.Collections;

namespace Battle.View
{
    public class DropAngerBallUI : MonoBehaviour
    {
        public float duration = 0.3f;

        public float startX;
        public float startY;
        public float targetX = -400f;
        public float targetY = -300f;

        public float speed;
        Vector3 dir;
        bool isRunning = false;

        public void Run(GameObject angerBall)
        {
            var tmpVec = Vector3.one;
            tmpVec = BattleViewCtrl.GetInstance().battleCamera.WorldToScreenPoint(tmpVec);
            tmpVec = UICamera.currentCamera.ScreenToWorldPoint(tmpVec);

            var pos = angerBall.transform.position;
            pos = BattleViewCtrl.GetInstance().battleCamera.WorldToScreenPoint(pos);
            pos = UICamera.currentCamera.ScreenToWorldPoint(pos);
            pos.z = 0f;
            transform.SetParent(BattleManager.Instance.battlePanel.wordAnchor);
            transform.position = pos;
            transform.localScale = tmpVec;
            transform.localEulerAngles = Vector3.zero;

            startX = transform.localPosition.x;
            startY = transform.localPosition.y;
            var dis = Vector2.Distance(new Vector2(startX, startY), new Vector2(targetX, targetY));
            speed = dis / duration;
            dir = new Vector3(targetX - startX, targetY - startY, 0);
            dir = dir.normalized;
            isRunning = true;
        }

        void Update()
        {
            if (isRunning)
            {
                var newPos = transform.localPosition + dir * Time.deltaTime * speed;
                transform.localPosition = newPos;
                if (Vector3.Distance(transform.localPosition, new Vector3(targetX, targetY, 0)) <= Time.deltaTime * speed) {
                    isRunning = false;
                    BattleFactory.UnSpawn(gameObject);
                }
            }
        }

    }
}